package com.java110.mall.chain.supplier.print;

import com.alibaba.fastjson.JSONObject;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.core.log.LoggerFactory;
import com.java110.dto.shop.ShopDto;
import com.java110.dto.shop.ShopPrinterMachineDto;
import com.java110.dto.storeOrder.StoreOrderDto;
import com.java110.dto.storeOrder.StoreOrderAddressDto;
import com.java110.dto.storeOrder.StoreOrderCartDto;
import com.java110.dto.storeOrderWriteoff.StoreOrderWriteoffDto;
import com.java110.intf.cart.IStoreOrderAddressInnerServiceSMO;
import com.java110.intf.cart.IStoreOrderCartInnerServiceSMO;
import com.java110.intf.shop.IShopInnerServiceSMO;
import com.java110.intf.shop.IShopPrinterLogV1InnerServiceSMO;
import com.java110.mall.chain.supplier.IOrderPrintAdapter;
import com.java110.mall.chain.supplier.print.yilanyun.RequestMethod;
import com.java110.po.shop.ShopPrinterLogPo;
import com.java110.utils.cache.CommonCache;
import com.java110.utils.util.DateUtil;
import com.java110.utils.util.ListUtil;
import com.java110.utils.util.StringUtil;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("yilanyunOrderPrintAdapter")
public class YilanyunOrderPrintAdapter implements IOrderPrintAdapter {

    private static Logger logger = LoggerFactory.getLogger(YilanyunOrderPrintAdapter.class);

    /**
     * 国内域名：https://open-api.10ss.net/v2
     * 境外域名（无需修改DNS）：https://open-api-os.10ss.net/v2
     * 如果您不想修改DNS，可以使用以下国内域名：https://cloud-open-api.10ss.net/v2
     * 请根据服务器所在区域合理的请求相应域名。
     */

    private static final String ACCESS_TOKEN = "Yilianyun2_access_token";

    @Autowired
    private IShopInnerServiceSMO shopInnerServiceSMOImpl;

    @Autowired
    private IStoreOrderCartInnerServiceSMO storeOrderCartInnerServiceSMOImpl;

    @Autowired
    private IStoreOrderAddressInnerServiceSMO storeOrderAddressInnerServiceSMOImpl;

    @Autowired
    private IShopPrinterLogV1InnerServiceSMO shopPrinterLogV1InnerServiceSMOImpl;

    @Override
    public void printOrder(ShopPrinterMachineDto shopPrinterMachineDto, StoreOrderDto storeOrderDto) {

        String content = "";

        ShopDto shopDto = new ShopDto();
        shopDto.setShopId(storeOrderDto.getShopId());
        List<ShopDto> shopDtos = shopInnerServiceSMOImpl.queryShops(shopDto);
        if (ListUtil.isNull(shopDtos)) {
            throw new IllegalArgumentException("店铺不存在");
        }
        StoreOrderCartDto storeOrderCartDto = new StoreOrderCartDto();
        storeOrderCartDto.setOrderId(storeOrderDto.getOrderId());
        List<StoreOrderCartDto> storeOrderCartDtos = storeOrderCartInnerServiceSMOImpl.queryStoreOrderCarts(storeOrderCartDto);
        if (ListUtil.isNull(storeOrderCartDtos)) {
            throw new IllegalArgumentException("未查询到订单明细");
        }
        StoreOrderAddressDto storeOrderAddressDto = new StoreOrderAddressDto();
        storeOrderAddressDto.setOrderId(storeOrderDto.getOrderId());
        List<StoreOrderAddressDto> storeOrderAddressDtos =
                storeOrderAddressInnerServiceSMOImpl.queryStoreOrderAddresss(storeOrderAddressDto);

        content += ("<FS2>" + shopDtos.get(0).getShopName() + "</FS2>\n");
        content += ("单号:" + storeOrderDto.getOrderId()+"\n");
        content += ("时间:" + DateUtil.getFormatTimeStringA(storeOrderDto.getCreateTime())+"\n");
        content += ("**************商品**************\n");
        content += ("<table>");
        for(StoreOrderCartDto tmpStoreOrderCartDto : storeOrderCartDtos) {
            content += ("<tr>");
            content += ("<td>"+tmpStoreOrderCartDto.getProdName()+"</td>");
            content += ("<td>x"+tmpStoreOrderCartDto.getCartNum()+"</td>");
            content += ("<td>￥"+tmpStoreOrderCartDto.getPayPrice()+"</td>");
            content += ("</tr>");
        }
        content += ("</table>\n");
        content += ("********************************\n");
        content += ("总原价:" + storeOrderDto.getTotalPrice()+"\n");
        content += ("实际支付: "+storeOrderDto.getPayPrice()+"\n");
        content += ("--------------------------------\n");
        if(!ListUtil.isNull(storeOrderAddressDtos)){
            content += ("顾客姓名: "+storeOrderAddressDtos.get(0).getUsername()+"\n");
            content += ("顾客电话: "+storeOrderAddressDtos.get(0).getTel()+"\n");
            content += ("顾客地址: "+storeOrderAddressDtos.get(0).getAddress()+"\n");
        }

        String printRes = "";
        try {
            printRes = doPrintOrder(content, shopPrinterMachineDto, storeOrderDto.getOrderId());
        } catch (Exception e) {
            e.printStackTrace();
            throw new IllegalArgumentException(e.getMessage());
        }finally {
            ShopPrinterLogPo shopPrinterLogPo = new ShopPrinterLogPo();
            shopPrinterLogPo.setResParam(printRes);
            shopPrinterLogPo.setMachineCode(shopPrinterMachineDto.getMachineCode());
            shopPrinterLogPo.setOrderId(GenerateCodeFactory.getGeneratorId("11"));
            shopPrinterLogPo.setShopName(shopDtos.get(0).getShopName());
            shopPrinterLogPo.setShopId(shopPrinterMachineDto.getShopId());
            shopPrinterLogPo.setReqParam(content);
            shopPrinterLogV1InnerServiceSMOImpl.saveShopPrinterLog(shopPrinterLogPo);
        }

    }

    @Override
    public void printReadyOrder(ShopPrinterMachineDto shopPrinterMachineDto, StoreOrderDto storeOrderDto, StoreOrderWriteoffDto storeOrderWriteoffDto) {
        String content = "";

        ShopDto shopDto = new ShopDto();
        shopDto.setShopId(storeOrderDto.getShopId());
        List<ShopDto> shopDtos = shopInnerServiceSMOImpl.queryShops(shopDto);
        if (ListUtil.isNull(shopDtos)) {
            throw new IllegalArgumentException("店铺不存在");
        }

        StoreOrderAddressDto storeOrderAddressDto = new StoreOrderAddressDto();
        storeOrderAddressDto.setOrderId(storeOrderDto.getOrderId());
        List<StoreOrderAddressDto> storeOrderAddressDtos =
                storeOrderAddressInnerServiceSMOImpl.queryStoreOrderAddresss(storeOrderAddressDto);

        content += ("<FS2>" + shopDtos.get(0).getShopName() + "</FS2>\n");
        content += ("核销单号:" + storeOrderWriteoffDto.getWoNum()+"\n");
        content += ("手机尾号:" + storeOrderWriteoffDto.getLinkNum()+"\n");
        content += ("单号:" + storeOrderDto.getOrderId()+"\n");
        content += ("时间:" + DateUtil.getFormatTimeStringA(storeOrderDto.getCreateTime())+"\n");
        content += ("总原价:" + storeOrderDto.getTotalPrice()+"\n");
        content += ("实际支付: "+storeOrderDto.getPayPrice()+"\n");
        content += ("--------------------------------\n");
        if(!ListUtil.isNull(storeOrderAddressDtos)){
            content += ("顾客姓名: "+storeOrderAddressDtos.get(0).getUsername()+"\n");
            content += ("顾客电话: "+storeOrderAddressDtos.get(0).getTel()+"\n");
            content += ("顾客地址: "+storeOrderAddressDtos.get(0).getAddress()+"\n");
        }
        content += ("--------------------------------\n");
        content += ("<QR>" + storeOrderWriteoffDto.getWoNum() + "</QR>\n");

        String printRes = "";
        try {
            printRes = doPrintOrder(content, shopPrinterMachineDto, storeOrderDto.getOrderId());
        } catch (Exception e) {
            e.printStackTrace();
            throw new IllegalArgumentException(e.getMessage());
        }finally {
            ShopPrinterLogPo shopPrinterLogPo = new ShopPrinterLogPo();
            shopPrinterLogPo.setResParam(printRes);
            shopPrinterLogPo.setMachineCode(shopPrinterMachineDto.getMachineCode());
            shopPrinterLogPo.setOrderId(storeOrderDto.getOrderId());
            shopPrinterLogPo.setShopName(shopDtos.get(0).getShopName());
            shopPrinterLogPo.setShopId(shopPrinterMachineDto.getShopId());
            shopPrinterLogPo.setReqParam(content);
            shopPrinterLogV1InnerServiceSMOImpl.saveShopPrinterLog(shopPrinterLogPo);
        }
    }

    private String doPrintOrder(String content, ShopPrinterMachineDto shopPrinterMachineDto, String orderId) throws Exception {

        String clientId = shopPrinterMachineDto.getAppId();
        String clientSecret = shopPrinterMachineDto.getAppSecure();
        // 初始化 请求 对象
        RequestMethod.getInstance().init(clientId, clientSecret);

        String accessToken = CommonCache.getValue(ACCESS_TOKEN + clientId);
        if (StringUtil.isEmpty(accessToken)) {
            accessToken = RequestMethod.getInstance().getAccessToken();
            JSONObject paramOut = JSONObject.parseObject(accessToken);
            if (paramOut.getIntValue("error") != 0) {
                throw new IllegalArgumentException(paramOut.getString("error_description"));
            }
            accessToken = paramOut.getJSONObject("body").getString("access_token");
            //参数：* @param refresh_token 更新access_token所需，有效时间35天
            //CommonCache.setValue(ACCESS_TOKEN + clientId, accessToken, 30 * 24 * 60 * 60);
            CommonCache.setValue(ACCESS_TOKEN + clientId, accessToken, 24 * 60 * 60);
        }

        String printRes = RequestMethod.getInstance().printIndex(accessToken, shopPrinterMachineDto.getMachineCode(), content, orderId);
        logger.debug("-------------------调用易联云打印机返回日志：{}", printRes);
        System.out.println("-------------------调用易联云打印机返回日志：" + printRes);
        return printRes;



    }
}
